from aiogram.types import Document, CallbackQuery
import pandas as pd
import table_processor

import json
import config

CACHE = {}
PARSED_EXCEL = None

async def save_file(file: Document):
    CACHE['name'] = file.file_name
    CACHE['id'] = file.file_id
    save_cache()
    path = config.get_bot_path() / file.file_name
    await file.download(destination_file=path)
    PARSED_EXCEL = pd.ExcelFile(path)
    table_processor.parse_tables()

async def get_file():
    path = config.get_bot_path() / CACHE['name']
    with path.open(mode='rb') as data:
        file = data.read()
        return file

def get_file_id():
    return CACHE['id']

def get_file_name():
    return CACHE['name']

def load_cache():
    global CACHE
    global PARSED_EXCEL
    cache_path = config.get_cache_path()
    try:
        with cache_path.open(mode='r') as cache:
            CACHE = json.load(cache)
            if 'name' in CACHE.keys():
                PARSED_EXCEL = pd.ExcelFile(config.get_bot_path() / CACHE['name'])
                print( CACHE['name'])
            else:
                ptint("b")
                PARSED_EXCEL = None
    except FileNotFoundError:
        CACHE = {'name': None, 'id': None}

def save_cache():
    cache_path = config.get_cache_path()
    with cache_path.open(mode='w') as cache_file:
        json.dump(CACHE, cache_file)

def get_excel():
    return PARSED_EXCEL